class VideoList {
    constructor() {
        console.log('初始化视频列表...');
        this.videoList = document.querySelector('.video-list');
        this.loadingSpinner = document.querySelector('.loading-spinner');
        
        if (!this.videoList) {
            console.error('找不到视频列表容器元素');
            return;
        }
        
        this.page = 1;
        this.pageSize = 10;
        this.loading = false;
        this.hasMore = true;

        this.init();
    }

    init() {
        console.log('开始加载视频...');
        // 初始化时加载第一页视频
        this.loadVideos();

        // 添加滚动监听，实现无限加载
        window.addEventListener('scroll', () => {
            if (this.isBottom() && !this.loading && this.hasMore) {
                console.log('滚动到底部，加载更多视频...');
                this.page++;
                this.loadVideos();
            }
        });
    }

    isBottom() {
        return window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 100;
    }

    async loadVideos() {
        if (this.loading) return;
        this.loading = true;
        this.showLoading();

        try {
            console.log(`正在加载第 ${this.page} 页视频...`);
            const response = await fetch(`/api/videos?page=${this.page}&pageSize=${this.pageSize}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            console.log('获取到视频数据:', data);

            if (!data.videos || data.videos.length === 0) {
                console.log('没有更多视频了');
                this.hasMore = false;
                return;
            }

            this.renderVideos(data.videos);
        } catch (error) {
            console.error('加载视频列表失败:', error);
            this.showError('加载视频列表失败，请稍后重试');
        } finally {
            this.hideLoading();
            this.loading = false;
        }
    }

    renderVideos(videos) {
        console.log(`开始渲染 ${videos.length} 个视频...`);
        videos.forEach(video => {
            const videoCard = this.createVideoCard(video);
            this.videoList.appendChild(videoCard);
        });
    }

    createVideoCard(video) {
        console.log('创建视频卡片:', video);
        const card = document.createElement('div');
        card.className = 'video-card';
        
        // 创建视频缩略图容器
        const thumbnailContainer = document.createElement('div');
        thumbnailContainer.className = 'video-thumbnail';
        
        // 创建图片元素用于显示缩略图
        const imgElement = document.createElement('img');
        imgElement.alt = video.title;
        
        // 创建时长显示元素
        const durationElement = document.createElement('div');
        durationElement.className = 'video-duration';
        
        // 如果有视频时长，直接显示
        if (video.duration) {
            durationElement.textContent = this.formatDuration(video.duration);
        } else {
            // 如果没有时长，创建视频元素来获取时长
            const videoElement = document.createElement('video');
            videoElement.className = 'video-preview';
            videoElement.preload = 'metadata';
            videoElement.muted = true;
            videoElement.src = video.url;
            
            // 当视频加载完成后，获取时长并显示
            videoElement.addEventListener('loadedmetadata', () => {
                durationElement.textContent = this.formatDuration(videoElement.duration);
                // 设置当前时间为第一帧
                videoElement.currentTime = 0;
            });
            
            // 如果图片加载失败，显示视频预览
            imgElement.onerror = () => {
                imgElement.style.display = 'none';
                videoElement.style.display = 'block';
                thumbnailContainer.appendChild(videoElement);
            };
        }
        
        // 设置图片源
        imgElement.src = video.thumbnail || '/images/default-thumbnail.jpg';
        imgElement.style.display = 'block';
        
        // 添加元素到容器
        thumbnailContainer.appendChild(imgElement);
        thumbnailContainer.appendChild(durationElement);
        
        // 获取作者头像路径
        let avatarPath = '/images/default-avatar.png';
        if (video.author && video.author.avatar) {
            // 确保头像路径从 /uploads/avatars/ 获取
            if (video.author.avatar.startsWith('/uploads/avatars/')) {
                avatarPath = video.author.avatar;
            } else if (video.author.avatar.startsWith('/uploads/')) {
                // 如果路径是 /uploads/xxx，转换为 /uploads/avatars/xxx
                avatarPath = '/uploads/avatars/' + video.author.avatar.split('/').pop();
            } else {
                // 如果只是文件名，添加前缀
                avatarPath = '/uploads/avatars/' + video.author.avatar;
            }
        }
        
        // 创建视频信息容器
        const infoContainer = document.createElement('div');
        infoContainer.className = 'video-info';
        infoContainer.innerHTML = `
            <h3 class="video-title">${video.title}</h3>
            <div class="video-meta">
                <div class="video-author">
                    <img src="${avatarPath}" alt="${video.author?.nickname || '未知用户'}" onerror="this.src='/images/default-avatar.png'">
                    <span>${video.author?.nickname || '未知用户'}</span>
                </div>
                <div class="video-stats">
                    <span><i class="fas fa-eye"></i> ${this.formatNumber(video.views || 0)}</span>
                    <span><i class="fas fa-heart"></i> ${this.formatNumber(video.favorites || 0)}</span>
                </div>
            </div>
            <p class="video-description">${video.description || '暂无描述'}</p>
        `;
        
        // 组装卡片
        card.appendChild(thumbnailContainer);
        card.appendChild(infoContainer);
        
        // 添加点击事件，跳转到视频详情页
        card.addEventListener('click', () => {
            window.location.href = `/video/${video.id}`;
        });

        return card;
    }

    formatDuration(seconds) {
        if (!seconds || isNaN(seconds)) return '0:00';
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = Math.floor(seconds % 60);
        return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
    }

    formatNumber(num) {
        if (num >= 10000) {
            return (num / 10000).toFixed(1) + 'w';
        }
        return num.toString();
    }

    showLoading() {
        if (this.loadingSpinner) {
            this.loadingSpinner.style.display = 'flex';
        }
    }

    hideLoading() {
        if (this.loadingSpinner) {
            this.loadingSpinner.style.display = 'none';
        }
    }

    showError(message) {
        const errorDiv = document.createElement('div');
        errorDiv.className = 'error-message';
        errorDiv.textContent = message;
        this.videoList.appendChild(errorDiv);
    }
}

// 初始化视频列表
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM加载完成，初始化视频列表...');
    new VideoList();
}); 